document.addEventListener("deviceready", onDeviceReadys, false);

function onDeviceReadys() {

	var db = window.openDatabase("Database", "1.0", "Status Voo", 200000);
	db.transaction(createDB, errorCB, successCB);

	$("#salvarHistorico").click(function() {
		var db = window.openDatabase("Database", "1.0", "Status Voo", 200000);
		db.transaction(insertHistorico, errorCB, successInsert);
	});

	$("#listar").click(function() {
		showLoadMsg();
		var db = window.openDatabase("Database", "1.0", "Status Voo", 200000);
		db.transaction(queryDB, errorCB);
	});

}

function createDB(tx) {
	//tx.executeSql('DROP TABLE IF EXISTS STATUS');
	tx.executeSql('CREATE TABLE IF NOT EXISTS STATUS (id INTEGER PRIMARY KEY, numeroVoo, codCompania)');
}

function insertHistorico(tx) {
	var numeroVoo = $("#listResult .numeroVoo").text();
	var codigoCompania = $("#listResult .codigoCompania").text();
	tx.executeSql('INSERT INTO STATUS (numeroVoo, codCompania) VALUES ("' + numeroVoo + '", "' + codigoCompania + '")');
}

function queryDB(tx) {
	tx.executeSql('SELECT * FROM STATUS', [], querySuccess, errorCB);
}

function querySuccess(tx, results) {

	var len = results.rows.length;

	if(len > 0){

		$("#listConsultas").text("");
		for (var i = 0; i < len; i++) {
			$("#listConsultas").append("ID ").append(results.rows.item(i).id).append(" | ").append(results.rows.item(i).codCompania).append(" ").append(results.rows.item(i).numeroVoo).append("<br />");
		}

		$("#consultas").show();
		hideLoadMsg();
	
	}else{
		hideLoadMsg();
		alert("Sem consultas salvas.");
		$("#consultas").hide();
	}
}

function errorCB(err) {
	alert("Erro ao processar SQL: " + err.code);
}

function successInsert() {
	alert("Consulta salva!");
}

function successCB() {
	console.log("Success DB");
}